<?php

namespace App\Http\Controllers\Steward;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Redis as Redis;
use App\Models\Mall\MallMaster;
use App\Models\Mall\MallUser;


class LoginController extends Controller
{

    const APPID = 'dcf7da0be34211e4882200163e00313a';

    const APPKEY = '5d6011fc3373d26cbc7916ff41878925';

    const REQUESTURL = 'http:www.ebsig.com';

    //用户登录页
    public function index(Request $request)
    {

        $redirect_url = $request->input('redirect_url');
        if (is_url($redirect_url)) {
            Redis::setex('WDH_STEWARD_LOGIN_REDIRECT_' . session_id(), 1800, $redirect_url);
        }

        return view('steward/login');
        
    }

    //登录操作
    public function login (Request $request)
    {

        $mobile = $request->input('mobile');
        $password = $request->input('password');

        if ( empty($mobile) ) {
            return response()->json(['code'=>100001, 'message'=>'手机号码不能为空']);
        } else if ( !isMobile($mobile) ) {
            return response()->json(['code'=>100001, 'message'=>'手机号格式错误']);
        }

        if ( empty($password)) {
            return response()->json(['code'=>100002, 'message'=>'登录密码不能为空']);
        }

        if ( !isPwd($password)) {
            return response()->json(['code'=>100003, 'message'=>'登录密码格式不正确']);
        }

        $mallUser = MallUser::where('mobile', $mobile)->first();
        if (!$mallUser) {
            return response()->json(['code'=>100004, 'message'=>'该用户不存在']);
        }

        if ($mallUser->pwd != md5($password)) {
            return response()->json(['code'=>100005, 'message'=>'用户密码不正确']);
        }

        if (!in_array($mallUser->userType, [1, 2])) {
            return response()->json(['code'=>100006, 'message'=>'登录用户身份不支持']);
        }

        if ($mallUser->userType == 1) {
            $mall_master = MallMaster::find($mallUser->mallID);
        } else {
            $mall_master = MallMaster::where('mallareaID', $mallUser->mallareaID)->first();
        }

        if (!$mall_master || $mall_master->useFlg == 0) {
            return response()->json(['code'=>100007, 'message'=>'门店信息没有找到']);
        }

        Redis::setex('WDH_STEWARD_MALL_ID_' . session_id(), 86400, $mall_master->mallID);
        Redis::setex('WDH_STEWARD_USER_ID_' . session_id(), 86400, $mallUser->user_id);

        $redirect_url = Redis::get('WDH_STEWARD_LOGIN_REDIRECT_' . session_id());
        if (!$redirect_url) {
            $redirect_url = '/lar/steward';
        }

        return response()->json([
            'code' => 200,
            'message' => '登录成功',
            'data' => ['redirect_url' => $redirect_url]
        ]);

    }

    //退出
    public function logout(Request $request)
    {

        $redirect_url = $request->input('redirect_url');

        $http_user_agent = $request->server('HTTP_USER_AGENT');
        $client_id = Redis::get('WDH_CLIENT_ID_' . session_id());
        if ( strpos($http_user_agent, '.NET CLR') ) {

            $request_data = [
                'appId' => self::APPID,
                'client_id' => $client_id,
                'params' =>''
            ];
            $request_data['sign'] = $this->create_sign($request_data, self::APPKEY);

            $client = new Client();
            $res = $client->get(self::REQUESTURL . '/lar/steward/client/notice?'.http_build_query($request_data));
            if ($res->getStatusCode() != 200) {
                return redirect($redirect_url);
            }

            $content =  $res->getBody()->getContents();
            $content = json_decode($content, true);
            if ($content['code'] != 200) {
                return redirect($redirect_url);
            }

        }

        Redis::del('WDH_STEWARD_MALL_ID_' . session_id());
        Redis::del('WDH_STEWARD_USER_ID_' . session_id());

        header('Location: /lar/steward/login?redirect_url=' . urlencode($redirect_url));

    }


    //签名验签
    private function create_sign($data, $key) {

        ksort($data);

        $sign_str = '';
        foreach ($data as $k => $v) {
            if ($v === '' || $k == 'sign' || $k == '_url' || $k == 'file' || $k == 'fileKey') {
                continue;
            }
            $sign_str .= $k . '=' . $v;
        }

        $sign_str .= $key;
        return strtoupper(md5($sign_str));

    }
    
}
